package com.tianlaiedu.controller;

import com.alibaba.fastjson.JSON;
import com.tianlaiedu.bean.ResultVO;
import com.tianlaiedu.bean.User;
import com.tianlaiedu.bean.Userdata;
import com.tianlaiedu.service.impl.UserDataServiceImpl;
import com.tianlaiedu.service.impl.UserServiceImpl;
import com.tianlaiedu.utils.CodeUtil;
import com.tilaiedu.framework.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:hejing
 * @date:2021/11/26
 */
public class Login {
    private static final Logger LOGGER = LoggerFactory.getLogger(Login.class);

    @RequestMapping("/user/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServerException {
        // 先设置相应的字符编码
        request.setCharacterEncoding("utf-8");
        // 如果浏览器传入的是json数据，就不能使用 request.getParameter("")获取数据
        // 通过json功能类来获取json数据
        Map<String, Object> res = JSON.parseObject(request.getInputStream(), HashMap.class);
        LOGGER.debug("=>前端传入的数据:" + res);
        // 先获取用户输入的验证码数据
        String checkcode = (String) res.get("checkcode");
        LOGGER.debug("=>checkcode = " + checkcode);
        // 定义一个返回值对象
        ResultVO resultVO = new ResultVO();
        // 比较两个验证码是否相同
        HttpSession session = request.getSession();
        String imgCode = (String) session.getAttribute("checkcode");
        response.setContentType("application/json;charset=utf-8");
        if (checkcode == null) return;
        if (!checkcode.equalsIgnoreCase(imgCode)) {
            LOGGER.info(checkcode);
            resultVO.setMessage("验证码错误");
            response.getWriter().write(JSON.toJSONString(resultVO));
            LOGGER.warn("=>验证码错误");
            return;
        }
        // 获取表单数据
        String username = (String) res.get("name");
        String password = (String) res.get("pwd");
        //// 调用登录验证
        System.out.println("name" + username + "       pwd" + password);
        User user = new UserServiceImpl().findUser(username, password);
        if (user != null) {
            // 如果登录成功，同时将用户对象保存到sesson中，在过滤器中就可以或session中的用户判断是否有值
            session.setAttribute("user", user);
            // 将当前的登录ip添加到session中
            String ip = request.getRemoteHost();
            session.setAttribute("loginIp", ip);
            // 将当前的日期添加session中
            session.setAttribute("loginDate", new Date());
            //将sessionid添加到作用域
            request.getServletContext().setAttribute(session.getId(), session);
            // 实现7天免登录，让当前的session对象的存活时间设置为7天
            // 先获取用户是否勾选了记住我
            boolean saveme = (boolean) res.get("saveme");
            LOGGER.info("=>用户是否选择记住我:" + saveme);
            // 说明用户勾选了记住我,设置session的存活时长
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            if (saveme) {
                // 7天免登录
                cookie.setMaxAge(7 * 24 * 60 * 60);
            } else {
                // 取消7天免登录
                cookie.setMaxAge(-1);
            }
            response.addCookie(cookie);
            // 设置相应数据返回给调用者
            resultVO.setMessage("登录成功");
            resultVO.setType(0);
            resultVO.setData(user);
            LOGGER.info("=>登录成功:" + user);
        } else {
            resultVO.setMessage("账号密码错误");
            resultVO.setType(1);
            LOGGER.error("=>账号密码错误");
        }
        response.getWriter().write(JSON.toJSONString(resultVO));
    }

    @RequestMapping("/user/zhuce")
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServerException {
        request.setCharacterEncoding("utf-8");
        // 通过json功能类来获取json数据
        Map<String, Object> res = JSON.parseObject(request.getInputStream(), HashMap.class);
        LOGGER.debug("=>前端传入的数据:" + res);
        if (res==null){
            System.out.println("res = " + res);
            return;
        }

        User user = new User();
        user.setUsername((String) res.get("name"));
//        查询用户名是否重复
        ResultVO resultVO = new ResultVO();
        User userByname = new UserServiceImpl().findUserByname(user.getUsername());
        if (userByname!=null){
            response.setContentType("application/json;charset=utf-8");
            resultVO.setMessage("用户名重复！");
            response.getWriter().write(JSON.toJSONString(resultVO));
            return;
        }
        user.setPassword((String) res.get("pwd1"));
//        向数据库添加用户
        UserDataServiceImpl userDataService = new UserDataServiceImpl();
        UserServiceImpl userService = new UserServiceImpl();

        if (userService.addUser(user) > 0) {
            user = userService.findUser((String) res.get("name"), (String) res.get("pwd1"));
            Userdata userdata = new Userdata();
            //将用户数据表关联起来
            userdata.setId(user.getId());
            if (userDataService.addUserData(userdata) > 0) {
                resultVO.setType(0);
            }
        }
        response.setContentType("application/json;charset=utf-8");
        if (resultVO.getTotal() != null) {
            response.getWriter().write(JSON.toJSONString(resultVO));
        } else {
            resultVO.setMessage("操作失败");
            response.getWriter().write(JSON.toJSONString(resultVO));
        }
    }

    @RequestMapping("/user/getCheckCode")
    public void getCheckCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得验证码
        String checkCode = CodeUtil.getCheckCode();
        LOGGER.info("checkcodeServlet = " + checkCode);
        // 将验证码保存到session中，让登录的servlet可以使用
        request.getSession().setAttribute("checkcode", checkCode);
        // 获得图片
        CodeUtil.outputImage(response.getOutputStream());
    }

    @RequestMapping("/user/who")
    public void getWho(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LOGGER.info("" + req.getSession().getAttribute("user"));
        if (req.getSession().getAttribute("user") != null) {
            // 获取session中的用户信息
            Object user = req.getSession().getAttribute("user");
            user.toString();
            LOGGER.info(user.toString());
            // 相应给调用者
            resp.setContentType("application/json;charset=utf-8");
            // 相应json数据
            resp.getWriter().write(JSON.toJSONString(user));
        } else {
            System.out.println("从域对象加载session");
            //user信息不在服务器
//            获取session对象的id
            if (req.getSession().getId() != null) {
                String sessionid = (String) req.getSession().getId();
                System.out.println("sessionid = " + sessionid);

                Object user = req.getServletContext().getAttribute(sessionid);
                System.out.println("user = " + user);
                // 相应给调用者
                resp.setContentType("application/json;charset=utf-8");
                // 相应json数据
                resp.getWriter().write(JSON.toJSONString(user));
            } else {
                return;
            }

        }

    }

    @RequestMapping("/user/whodata")
    public void getData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取session中的用户信息
        User user = (User) req.getSession().getAttribute("user");

        System.out.println("user = " + user);
//        查询userdata
        Userdata userdata = new UserDataServiceImpl().findByid(user.getId());
        System.out.println("userdata = " + userdata);
        // 相应给调用者
        resp.setContentType("application/json;charset=utf-8");
        // 相应json数据
        resp.getWriter().write(JSON.toJSONString(userdata));

    }

    /**
     * 退出当前用户
     */
    @RequestMapping("/user/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 推出登录
        // 1. 直接移除当前session中的user  2. 让当前的session直接失效
        request.getSession().removeAttribute("user");
        // 直接让当前的会话session失效
        request.getSession().invalidate();

        ResultVO resultVO = new ResultVO();
        resultVO.setType(0);
        response.getWriter().write(JSON.toJSONString(resultVO));
    }
//    上传头像

}
